import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  SafeAreaView,
  TextInput,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Modal,
  Image,
  StatusBar,
  Animated,
  ActivityIndicator,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getStatusBarHeight } from '../../utils/statusBarHeight';
import { Toast } from '@ant-design/react-native';
import {
  scanBatchQrcodeApi,
  apsWorkNewApi,
  inStationApi,
  outStationApi,
  logoutApi,
  getDomainDictByTypeEn,
  getProcessResourceListApi,
  scanApi,
  getMBomByProductEncodeNewApi,
  getMesTaskByWorkOrderAndMbomNewApi
} from './api';
import CustomQRScanner from '../../components/CustomQRScanner';
import dingdongImg from '../../assets/dingdong.png';
import fanhui from '../../assets/fanhui.png';
import outlogin from '../../assets/outlogin.png';
import saoma from '../../assets/sma.png';
import zwsj from '../../assets/zwsj.png';

interface WorkInfo {
  id?: string;
  original_mbom_id?: string;  // 原始工序ID（用于调用getMesTaskByWorkOrderAndMbomNew接口）
  work_order_num: string;
  work_order_id?: string;  // 工单ID
  mbom_id?: string;        // 工序ID
  product_name: string;
  product_encode: string;
  product_specs: string;
  mbom_num: string;
  process_name: string;
  process_num?: string;  // 工序号
  process_color?: string; // 工序颜色
  bom_color?: string;    // BOM颜色
  workQuantity?: string;
  fatalQuantity?: string;
  testTime?: string;
  waitingTimeType?: string;
  station_state: boolean;
}

interface WaitingTimeType {
  id: string;
  kk: string;
  vv: string;
  sort: number;
}

const WorkReportScreen: React.FC<{ onLogout: () => void }> = ({ onLogout }) => {
  const [qrcode, setQrcode] = useState('');
  const [workInfo, setWorkInfo] = useState<WorkInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [scanVisible, setScanVisible] = useState(false);
  const [leftScanVisible, setLeftScanVisible] = useState(false);
  const [leftScanResult, setLeftScanResult] = useState('');
  const [leftScanData, setLeftScanData] = useState<any>(null); // 保存扫码接口返回的完整数据
  const [leftScanCapacity, setLeftScanCapacity] = useState<number | null>(null); // 保存扫码的capacity类型
  const [userNum, setUserNum] = useState(''); // 用户号，从登录信息获取
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  const [waitingTimeTypes, setWaitingTimeTypes] = useState<WaitingTimeType[]>([]);
  const [currentProcessIndex, setCurrentProcessIndex] = useState<number>(0); // 当前选中的工序索引
  const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const [dataUpdateKey, setDataUpdateKey] = useState<number>(0); // 数据更新标记

  // 设备选择相关状态 - 为每个工单单独管理
  const [resourceData, setResourceData] = useState<{
    [key: string]: {
      capacity: number | null;
      deviceList: any[];
      selectedDevice: string;
    }
  }>({});

  // 下拉框显示状态
  const [deviceDropdownVisible, setDeviceDropdownVisible] = useState(false);
  const [deviceArrowRotation] = useState(new Animated.Value(0));

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  // 初始化资源数据为空，通过接口获取
  useEffect(() => {
    setResourceData({});
  }, []);

  // 获取用户号
  const getUserNum = async () => {
    try {
      // 从AsyncStorage中获取保存的用户信息
      const userInfo = await AsyncStorage.getItem('userInfo');
      if (userInfo) {
        const user = JSON.parse(userInfo);
        console.log('获取到的用户信息:', user);
        // 根据实际登录接口返回的字段名获取用户号
        const userNum = user.user_name || user.num || user.username || user.userName || '';
        setUserNum(userNum);
        console.log('设置用户号:', userNum);
      } else {
        console.log('没有找到用户信息');
        setUserNum('');
      }
    } catch (error) {
      console.log('获取用户号失败:', error);
      setUserNum('');
    }
  };

  // 组件加载时获取用户号
  useEffect(() => {
    getUserNum();
  }, []);

  // 当工单数据更新时，自动选择第一个工序
  useEffect(() => {
    if (dataUpdateKey > 0 && workInfo.length > 0) {
      // 延迟执行，确保数据已经设置
      const timer = setTimeout(() => {
        handleProcessChange(0);
      }, 100);

      return () => clearTimeout(timer);
    } else if (workInfo.length === 0) {
      setCurrentProcessIndex(0);
      setSelectedIndex(null);
    }
  }, [dataUpdateKey]); // 监听数据更新标记

  // 确保currentProcessIndex始终在有效范围内
  useEffect(() => {
    if (workInfo.length > 0 && currentProcessIndex >= workInfo.length) {
      setCurrentProcessIndex(0);
      setSelectedIndex(0);
    }
  }, [workInfo.length, currentProcessIndex]);



  // 防抖搜索函数
  const debouncedSearch = (searchValue: string) => {
    // 清除之前的定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // 设置新的定时器，500ms后执行搜索
    searchTimeoutRef.current = setTimeout(() => {
      if (searchValue.trim()) {
        handleScanWithValue(searchValue.trim());
      } else {
        setWorkInfo([]);
      }
    }, 500);
  };

  // 扫码查询工单
  const handleScan = async () => {
    if (!qrcode) {
      Toast.info('请输入二维码内容', 1);
      return;
    }
    setLoading(true);
    try {
      const res = await scanBatchQrcodeApi({ qrcode });
      // 初始化每个工单的输入状态，并保存原始工序ID
      const data = (res.data || []).map((item: WorkInfo) => ({
        ...item,
        original_mbom_id: item.id, // 保存原始工序ID
        workQuantity: '',
        fatalQuantity: '',
        testTime: '',
        waitingTimeType: ''
      }));
      setWorkInfo(data);
      setDataUpdateKey(prev => prev + 1); // 触发自动选择
      Toast.success(res.msg || '工单信息已获取', 1);
    } catch (e: any) {
      console.log('扫码查询接口异常:', e);
      Toast.fail(e.message || '未知错误', 1);
      setWorkInfo([]);
    } finally {
      setLoading(false);
    }
  };

  // 参数类型单选接口
  const handleGetDomainDict = async () => {
    try {
      const res = await getDomainDictByTypeEn({ type_en: 'reporting_waiting_time' });
      if (res && res.code === 200 && res.data) {
        setWaitingTimeTypes(res.data);
      }
    } catch (error) {
      console.log('获取等待时间类型失败:', error);
    }
  };
  useEffect(() => {
    handleGetDomainDict();
  }, []);

  // 带值的搜索函数
  const handleScanWithValue = async (searchValue: string) => {
    setLoading(true);
    try {
      const res = await scanBatchQrcodeApi({ qrcode: searchValue });
      // 初始化每个工单的输入状态，并保存原始工序ID
      const data = (res.data || []).map((item: WorkInfo) => ({
        ...item,
        original_mbom_id: item.id, // 保存原始工序ID
        workQuantity: '',
        fatalQuantity: '',
        testTime: '',
        waitingTimeType: ''
      }));
      setWorkInfo(data);
      if (data.length > 0) {
        setDataUpdateKey(prev => prev + 1); // 触发自动选择
        Toast.success(res.msg || '工单信息已获取', 1);
      }
    } catch (e: any) {
      console.log('扫码查询接口异常:', e);
      Toast.fail(e.message || '未知错误', 1);
      setWorkInfo([]);
    } finally {
      setLoading(false);
    }
  };

  // 输入框变更
  const handleInputChange = (idx: number, key: 'workQuantity' | 'fatalQuantity' | 'testTime', value: string) => {
    setWorkInfo(prev => {
      const next = [...prev];
      next[idx] = { ...next[idx], [key]: value };
      return next;
    });
  };

  // 二维码输入框变更
  const handleQrcodeChange = (value: string) => {
    setQrcode(value);
    debouncedSearch(value);
  };

  // 报工
  const handleReport = async (idx: number) => {
    const item = workInfo[idx];
    setLoading(true);
    try {
      const resource = item.id ? resourceData[item.id] : null;

      // 验证完工数量
      if (!item.workQuantity || item.workQuantity.trim() === '') {
        Toast.fail('请输入完工数量', 1);
        setLoading(false);
        return;
      }

      // 根据capacity值进行验证和参数设置
      if (resource?.capacity === 1 || resource?.capacity === 5) {
        if (!leftScanResult || !leftScanData || !leftScanCapacity) {
          Toast.fail('请在左上角扫码绑定工位或产线', 1);
          setLoading(false);
          return;
        }

        // 检查扫码类型是否与当前工序匹配
        if (resource?.capacity === 1 && leftScanCapacity !== 1) {
          Toast.fail('请扫描工位二维码', 1);
          setLoading(false);
          return;
        }

        if (resource?.capacity === 5 && leftScanCapacity !== 5) {
          Toast.fail('请扫描产线二维码', 1);
          setLoading(false);
          return;
        }
      }

      const params = {
        task_id: item.id,
        work_quantity: item.workQuantity || '',
        fatal_quantity: item.fatalQuantity || '',
        wait_time: item.testTime || '',
        wait_time_type: item.waitingTimeType || '',
        work_order_num: item.work_order_num,
        mbom_num: item.mbom_num,
        process_name: item.process_name,
        // 根据capacity值传递不同参数
        ...(resource?.capacity === 1 && { station_num: leftScanData?.station_num || '' }),
        ...(resource?.capacity === 2 && { work_device_id: resource.selectedDevice || '' }),
        ...(resource?.capacity === 4 && { user_num: userNum }),
        ...(resource?.capacity === 5 && { line_num: leftScanData?.line_num || '' }),
      };
      console.log('报工提交参数:', params);
      console.log('当前工单ID:', item.id);
      console.log('当前capacity值:', resource?.capacity);
      console.log('左上角扫码结果:', leftScanResult);
      console.log('左上角扫码数据:', leftScanData);
      console.log('扫码capacity类型:', leftScanCapacity);
      console.log('用户号:', userNum);
      console.log('选中的设备ID:', resource?.selectedDevice);
      const res = await apsWorkNewApi(params);
      Toast.success(res.msg || '操作成功', 1);

      // 报工成功后清除输入值
      setWorkInfo(prev => {
        const next = [...prev];
        next[idx] = {
          ...next[idx],
          workQuantity: '',
          fatalQuantity: '',
          testTime: '',
          waitingTimeType: ''
        };
        return next;
      });

      // 清除设备选择状态
      if (item.id && resourceData[item.id]) {
        setResourceData(prev => ({
          ...prev,
          [item.id!]: {
            ...prev[item.id!],
            selectedDevice: ''
          }
        }));
      }

    } catch (e: any) {
      console.log('报工接口异常:', e);
      Toast.fail(e.message || '未知错误', 1);
    } finally {
      setLoading(false);
    }
  };

  // 新增开始和结束处理函数
  const handleStart = async (item: WorkInfo, idx: number) => {
    try {
      const res = await inStationApi({ task_id: item.id });
      // 本地更新
      if (res && res.code === 200) {
        setWorkInfo(prev => {
          const next = [...prev];
          next[idx] = { ...next[idx], station_state: true };
          return next;
        });
      }
    } catch (e: any) {
      Toast.fail(e.message || '未知错误', 1);
    }
  };

  const handleEnd = async (item: WorkInfo, idx: number) => {
    try {
      const res = await outStationApi({ task_id: item.id });
      if (res && res.code === 200) {
        // 本地更新
        setWorkInfo(prev => {
          const next = [...prev];
          next[idx] = { ...next[idx], station_state: false };
          return next;
        });
      }
    } catch (e: any) {
      Toast.fail(e.message || '未知错误', 1);
    }
  };

  const onScanPress = () => {
    setScanVisible(true);
  };

  const onLeftScanPress = () => {
    setLeftScanVisible(true);
  };

  const onLeftBarcodeScan = async (data: string) => {
    setLeftScanVisible(false);

    try {
      // 调用扫码接口
      const res = await scanApi({ qrcode: data });
      // 根据接口返回结果显示内容
      if (res && res.code === 200 && res.data) {
        // 根据capacity值获取对应的字段
        const capacity = res.data.capacity;
        let displayValue = '';

        if (capacity === 1) {
          // capacity=1时显示station_num
          displayValue = res.data.station_num || res.data.station_name || '';
        } else if (capacity === 5) {
          // capacity=5时显示line_num
          displayValue = res.data.line_num || res.data.line_name || '';
        }

        if (displayValue) {
          setLeftScanResult(displayValue);
          setLeftScanData(res.data); // 保存完整的接口返回数据
          setLeftScanCapacity(capacity); // 保存扫码的capacity类型
          Toast.success('绑定工位或产线成功', 1);
        } else {
          Toast.fail('未获取到有效的工位或产线信息', 1);
        }
      } else {
        Toast.fail(res.msg || '绑定工位或产线失败', 1);
      }
    } catch (error) {
      console.log('绑定工位或产线接口调用失败:', error);
      Toast.fail('绑定工位或产线失败，请重试', 1);
    }
  };

  const onBarcodeScan = (data: string) => {
    setScanVisible(false);

    try {
      // 尝试解析JSON数据
      const parsedData = JSON.parse(data);
      console.log('扫码解析数据:', parsedData);

      // 提取零件号和销售单号
      const productEncode = parsedData['零件号'];
      const salesOrderNum = parsedData['销售单号'];

      if (!productEncode || !salesOrderNum) {
        Toast.fail('二维码格式错误，缺少零件号或销售单号', 1);
        return;
      }

      // 将零件号显示到输入框
      setQrcode(productEncode);

      // 使用新接口进行搜索
      setTimeout(() => {
        handleScanWithNewApi(productEncode, salesOrderNum);
      }, 500);

    } catch (error) {
      console.log('JSON解析失败:', error);
      Toast.fail('二维码格式错误，请扫描正确的标签', 1);
    }
  };

  // 扫码专用：使用新接口根据产品编码和销售单号获取工单
  const handleScanWithNewApi = async (productEncode: string, salesOrderNum: string) => {
    setLoading(true);
    try {
      const res = await getMBomByProductEncodeNewApi({
        product_encode: productEncode,
        sales_order_num: salesOrderNum
      });
      // 初始化每个工单的输入状态，并保存原始工序ID
      const data = (res.data || []).map((item: WorkInfo) => ({
        ...item,
        original_mbom_id: item.id, // 保存原始工序ID
        workQuantity: '',
        fatalQuantity: '',
        testTime: '',
        waitingTimeType: ''
      }));
      setWorkInfo(data);
      setDataUpdateKey(prev => prev + 1); // 触发自动选择
      Toast.success(res.msg || '工单信息已获取', 1);
    } catch (e: any) {
      console.log('扫码查询接口异常:', e);
      Toast.fail(e.message || '未知错误', 1);
      setWorkInfo([]);
    } finally {
      setLoading(false);
    }
  };

  // 原有的搜索函数（保留用于其他地方调用）
  const handleScanWithData = async (scanData: string) => {
    if (!scanData) {
      Toast.info('请输入二维码内容', 1);
      return;
    }
    setLoading(true);
    try {
      const res = await scanBatchQrcodeApi({ qrcode: scanData });
      // 初始化每个工单的输入状态，并保存原始工序ID
      const data = (res.data || []).map((item: WorkInfo) => ({
        ...item,
        original_mbom_id: item.id, // 保存原始工序ID
        workQuantity: '',
        fatalQuantity: '',
        testTime: '',
        waitingTimeType: ''
      }));
      setWorkInfo(data);
      setDataUpdateKey(prev => prev + 1); // 触发自动选择
      Toast.success(res.msg || '工单信息已获取', 1);
    } catch (e: any) {
      console.log('扫码查询接口异常:', e);
      Toast.fail(e.message || '未知错误', 1);
      setWorkInfo([]);
    } finally {
      setLoading(false);
    }
  };

  // 退出登录
  const handleLogout = async () => {
    try {
      // 调用退出登录接口
      const res = await logoutApi();
      // 清除本地存储的token
      await AsyncStorage.removeItem('token');
      // 显示退出成功提示
      Toast.success(res.msg || '已安全退出登录', 1);
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        onLogout();
      }, 500);
    } catch (e: any) {
      console.log('退出登录接口异常:', e);
      // 即使接口调用失败，也清除本地token并跳转
      await AsyncStorage.removeItem('token');
      Toast.fail(e.message || '网络错误，但已清除本地登录状态', 1);
      // 延迟跳转
      setTimeout(() => {
        onLogout();
      }, 500);
    }
  };

  // 设备选择处理
  const handleDeviceSelect = (deviceId: string, workId: string) => {
    setResourceData(prev => ({
      ...prev,
      [workId]: {
        ...prev[workId],
        selectedDevice: deviceId
      }
    }));
    setDeviceDropdownVisible(false);
    // 关闭时重置动画
    Animated.timing(deviceArrowRotation, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };

  // 切换设备下拉框显示状态
  const toggleDeviceDropdown = () => {
    const toValue = deviceDropdownVisible ? 0 : 1;
    setDeviceDropdownVisible(!deviceDropdownVisible);
    Animated.timing(deviceArrowRotation, {
      toValue,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };


  // 获取设备显示文本
  const getDeviceDisplayText = (workId: string) => {
    const resource = resourceData[workId];
    if (!resource || !resource.selectedDevice) return '请选择设备';
    const device = resource.deviceList.find(d => d.id === resource.selectedDevice);
    return device ? `${device.name} (${device.code})` : '请选择设备';
  };


  // 工序切换处理
  const handleProcessChange = async (index: number) => {
    // 确保索引在有效范围内
    if (index >= 0 && index < workInfo.length) {
      setCurrentProcessIndex(index);
      setSelectedIndex(index);

      const selectedProcess = workInfo[index];

      // 使用原始工序ID调用获取任务数据接口
      const mbomIdForQuery = selectedProcess.original_mbom_id || selectedProcess.id;

      if (selectedProcess.work_order_id && selectedProcess.mbom_num && mbomIdForQuery) {
        try {
          const taskRes = await getMesTaskByWorkOrderAndMbomNewApi({
            work_order_id: selectedProcess.work_order_id,
            mbom_num: selectedProcess.mbom_num,
            mbom_id: mbomIdForQuery  // 使用原始工序ID
          });

          // 获取新的任务ID
          let newTaskId = selectedProcess.id;

          // 更新选中工序的数据
          if (taskRes && taskRes.data) {
            // 保存新返回的任务ID
            newTaskId = taskRes.data.id || selectedProcess.id;

            setWorkInfo(prev => {
              const next = [...prev];
              next[index] = {
                ...next[index],
                ...taskRes.data,
                // 保留原始工序ID（不被覆盖）
                original_mbom_id: next[index].original_mbom_id,
                // 保留原有的输入值
                workQuantity: next[index].workQuantity,
                fatalQuantity: next[index].fatalQuantity,
                testTime: next[index].testTime,
                waitingTimeType: next[index].waitingTimeType
              };
              return next;
            });
          }

          // 使用新的任务ID获取资源列表
          if (newTaskId) {
            handleGetResourceList(newTaskId);
          }
        } catch (error: any) {
          console.log('获取任务数据失败:', error);
          Toast.fail(error.message || '获取任务数据失败', 1);
        }
      } else {
        // 如果没有必要参数，直接用当前ID获取资源列表
        if (selectedProcess.id) {
          handleGetResourceList(selectedProcess.id);
        }
      }
    } else {
      // 如果索引超出范围，重置为0
      if (workInfo.length > 0) {
        setCurrentProcessIndex(0);
        setSelectedIndex(0);
      }
    }
  };

  // 获取资源列表
  const handleGetResourceList = async (workId: string) => {
    try {
      const res = await getProcessResourceListApi({ id: workId });

      if (res && res.data) {
        const capacity = res.data.capacity;
        // 为当前工单创建资源数据
        const newResourceData = {
          capacity,
          deviceList: [],
          selectedDevice: ''
        };

        // 只有当capacity为2时才处理设备资源
        if (capacity === 2 && res.data.device_list) {
          newResourceData.deviceList = res.data.device_list.map((device: any) => ({
            id: device.id,
            name: device.device_name,
            code: device.device_num,
            color: device.color
          }));
        }

        // 更新对应工单的资源数据
        setResourceData(prev => ({
          ...prev,
          [workId]: newResourceData
        }));
      } else {
        setResourceData(prev => ({
          ...prev,
          [workId]: {
            capacity: null,
            deviceList: [],
            selectedDevice: ''
          }
        }));
      }
    } catch (error) {
      Toast.fail('获取资源列表失败', 1);
      setResourceData(prev => ({
        ...prev,
        [workId]: {
          capacity: null,
          deviceList: [],
          selectedDevice: ''
        }
      }));
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar
        barStyle="dark-content"
        backgroundColor="#fff"
        translucent={true}
      />
      {/* 顶部固定区域 */}
      <View style={styles.headerContainer}>
        <View style={styles.header} >
          <TouchableOpacity onPress={onLeftScanPress} style={styles.headerLeftBtn}>
            {leftScanResult ? (
              <View style={styles.scanResultDisplay}>
                <Text
                  style={styles.scanResultText}
                  numberOfLines={1}
                  ellipsizeMode="tail"
                >
                  {leftScanResult || '无内容'}
                </Text>
                <Image source={saoma} style={styles.scanResultIcon} />
              </View>
            ) : (
              <Image source={saoma} style={{ width: 24, height: 24, tintColor: '#333' }} />
            )}
          </TouchableOpacity>
          <Text style={styles.title}>报工</Text>
          <TouchableOpacity onPress={handleLogout} style={styles.headerRightBtn}>
            <Image source={outlogin} style={{ width: 24, height: 24, tintColor: '#333' }} />
          </TouchableOpacity>
        </View>
      </View>

      {/* 固定搜索区域 */}
      <View style={styles.searchContainer}>
        <View style={styles.qrRow}>
          <View style={styles.inputContainer}>
            <TextInput
              style={styles.qrInput}
              placeholder="请扫描流转卡二维码"
              placeholderTextColor="#999"
              value={qrcode}
              onChangeText={handleQrcodeChange}
            />
            {qrcode.length > 0 && (
              <TouchableOpacity
                style={styles.clearButton}
                onPress={() => handleQrcodeChange('')}
              >
                <Text style={styles.clearButtonText}>×</Text>
              </TouchableOpacity>
            )}
          </View>

          <TouchableOpacity style={styles.qrBtn2} onPress={onScanPress} disabled={loading}>
            <Image source={saoma} style={[styles.qrBtnIcon, { tintColor: '#333' }]} />
          </TouchableOpacity>
        </View>
      </View>

      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        {/* 工序导航卡片 - 固定在顶部 */}
        {workInfo.length > 0 && (() => {
          return (
            <View style={styles.processSection}>
              <ScrollView
                horizontal
                showsHorizontalScrollIndicator={false}
                style={styles.processScrollView}
              >
                <View style={styles.processContainer}>
                  {workInfo.map((item, index) => (
                    <View key={item.id} style={styles.processItemContainer}>
                      <TouchableOpacity
                        style={[
                          styles.processItem,
                          { backgroundColor: item.process_color || '#ccc' },
                          currentProcessIndex === index && styles.selectedProcessItem
                        ]}
                        onPress={() => handleProcessChange(index)}
                      >
                        <View style={styles.processTextContainer}>
                          <Text style={styles.processNum}>{item.mbom_num || item.process_num}</Text>
                          <Text style={styles.processName} numberOfLines={2}>{item.process_name}</Text>
                        </View>
                        {currentProcessIndex === index && (
                          <View style={styles.completedIcon}>
                            <Text style={styles.checkmark}>✓</Text>
                          </View>
                        )}
                      </TouchableOpacity>
                      {index < workInfo.length - 1 && (
                        <View style={styles.processArrow}>
                          <Text style={styles.arrowText}>→</Text>
                        </View>
                      )}
                    </View>
                  ))}
                </View>
              </ScrollView>
            </View>
          );
        })()}

        {/* 工单信息展示 */}
        {workInfo.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Image source={zwsj} style={styles.emptyImage} />
            <Text style={styles.emptyText}>
              {loading ? '搜索中...' : qrcode ? '未找到相关工单' : '请扫描流转卡二维码'}
            </Text>
          </View>
        ) : (
          <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">

            {/* 当前选中工序的报工卡片 */}
            {workInfo.length > 0 && workInfo[currentProcessIndex] && (() => {
              const item = workInfo[currentProcessIndex];
              const idx = currentProcessIndex;
              return (
                <View
                  style={[
                    styles.infoBox,
                    {
                      backgroundColor: '#fff',
                      borderRadius: 8,
                      padding: 12,
                      marginBottom: 7,
                      elevation: 2,
                      borderColor: '#007AFF',
                      borderWidth: 2,
                      flexDirection: 'column',
                      position: 'relative',
                    },
                  ]}
                >
                  {/* 右上角对勾图标 */}
                  <Image
                    source={dingdongImg}
                    style={{ width: 20, height: 20, position: 'absolute', top: 8, right: 8, zIndex: 10 }}
                  />
                  <View style={{ flexDirection: 'row' }}>
                    <View style={{ flex: 1 }}>
                      <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>工单号：</Text>
                        <Text style={styles.infoValue}>{item.work_order_num || '-'}</Text>
                      </View>
                      <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>产品名称：</Text>
                        <Text style={styles.infoValue}>{item.product_name || '-'}</Text>
                      </View>
                      <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>产品编码：</Text>
                        <Text style={styles.infoValue}>{item.product_encode || '-'}</Text>
                      </View>
                      <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>产品规格：</Text>
                        <Text style={styles.infoValue}>{item.product_specs || '-'}</Text>
                      </View>
                      <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>工序号：</Text>
                        <Text style={styles.infoValue}>{item.mbom_num || '-'}</Text>
                      </View>
                      <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>工艺名称：</Text>
                        <Text style={styles.infoValue}>{item.process_name || '-'}</Text>
                      </View>
                    </View>
                    <View style={styles.actionCol}>
                      {item.station_state === false ? (
                        <TouchableOpacity
                          style={[styles.actionBtn, styles.startBtn]}
                          onPress={() => handleStart(item, idx)}
                        >
                          <Text style={styles.actionText}>开始</Text>
                        </TouchableOpacity>
                      ) : (
                        <TouchableOpacity
                          style={[styles.actionBtn, styles.endBtn]}
                          onPress={() => handleEnd(item, idx)}
                        >
                          <Text style={styles.actionText}>结束</Text>
                        </TouchableOpacity>
                      )}
                    </View>
                  </View>
                  <View style={styles.reportBox}>
                    {/* 当capacity为2时才显示设备选择 */}
                    {item.id && resourceData[item.id]?.capacity === 2 && (
                      <View style={styles.inputRow}>
                        <Text style={styles.inputLabel}>选择设备：</Text>
                        <View style={styles.deviceSelectorContainer}>
                          <TouchableOpacity
                            style={styles.deviceSelector}
                            onPress={toggleDeviceDropdown}
                          >
                            <Text style={styles.deviceSelectorText}>
                              {getDeviceDisplayText(item.id)}
                            </Text>
                            <Animated.Image
                              source={require('../../assets/xiala.png')}
                              style={[
                                styles.deviceArrow,
                                {
                                  transform: [{
                                    rotate: deviceArrowRotation.interpolate({
                                      inputRange: [0, 1],
                                      outputRange: ['0deg', '180deg']
                                    })
                                  }]
                                }
                              ]}
                            />
                          </TouchableOpacity>
                          {deviceDropdownVisible && (
                            <View style={styles.deviceDropdown}>
                              <ScrollView
                                showsVerticalScrollIndicator={false}
                                style={styles.deviceScrollView}
                                nestedScrollEnabled={true}
                              >
                                {resourceData[item.id]?.deviceList.map(device => (
                                  <TouchableOpacity
                                    key={device.id}
                                    style={styles.deviceOption}
                                    onPress={() => item.id && handleDeviceSelect(device.id, item.id)}
                                  >
                                    <Text style={styles.deviceOptionText}>
                                      {device.name} ({device.code})
                                    </Text>
                                  </TouchableOpacity>
                                ))}
                              </ScrollView>
                            </View>
                          )}
                        </View>
                      </View>
                    )}

                    {/* 当capacity为1时显示工位号提示 */}
                    {item.id && resourceData[item.id]?.capacity === 1 && (
                      <View style={styles.inputRow}>
                        <Text style={styles.inputLabel}>工位：</Text>
                        <Text style={styles.scanResultDisplayText}>
                          {leftScanResult || '请先扫码绑定工位'}
                        </Text>
                      </View>
                    )}

                    {/* 当capacity为4时显示用户号提示 */}
                    {item.id && resourceData[item.id]?.capacity === 4 && (
                      <View style={styles.inputRow}>
                        <Text style={styles.inputLabel}>人员：</Text>
                        <Text style={styles.scanResultDisplayText}>
                          {userNum || '未获取到用户信息'}
                        </Text>
                      </View>
                    )}

                    {/* 当capacity为5时显示产线号提示 */}
                    {item.id && resourceData[item.id]?.capacity === 5 && (
                      <View style={styles.inputRow}>
                        <Text style={styles.inputLabel}>产线：</Text>
                        <Text style={styles.scanResultDisplayText}>
                          {leftScanResult || '请先扫码绑定产线'}
                        </Text>
                      </View>
                    )}




                    <View style={styles.inputRow}>
                      <Text style={styles.inputLabel}>完工数量： </Text>
                      <TextInput
                        style={styles.input}
                        value={item.workQuantity || ''}
                        onChangeText={val => handleInputChange(idx, 'workQuantity', val)}
                        keyboardType="numeric"
                        placeholder="请输入完工数量"
                        placeholderTextColor="#999"
                      />
                    </View>
                    <View style={styles.inputRow}>
                      <Text style={styles.inputLabel}>报废数量：</Text>
                      <TextInput
                        style={styles.input}
                        value={item.fatalQuantity || ''}
                        onChangeText={val => handleInputChange(idx, 'fatalQuantity', val)}
                        keyboardType="numeric"
                        placeholder="请输入报废数量"
                        placeholderTextColor="#999"
                      />
                    </View>
                    <View style={styles.inputRow}>
                      <Text style={styles.inputLabel}>等待时间：</Text>
                      <TextInput
                        style={styles.input}
                        value={item.testTime || ''}
                        onChangeText={val => handleInputChange(idx, 'testTime', val)}
                        keyboardType="numeric"
                        placeholder="请输入等待时间(分钟)"
                        placeholderTextColor="#999"
                      />
                    </View>
                    <View style={styles.inputRow}>
                      <Text style={styles.inputLabel}>等待类型：</Text>
                      <View style={styles.radioGroup}>
                        {waitingTimeTypes.map((type) => (
                          <TouchableOpacity
                            key={type.id}
                            style={styles.radioItem}
                            onPress={() => {
                              setWorkInfo(prev => {
                                const next = [...prev];
                                next[idx] = { ...next[idx], waitingTimeType: type.kk };
                                return next;
                              });
                            }}
                          >
                            <View style={[
                              styles.radioCircle,
                              item.waitingTimeType === type.kk && styles.radioCircleSelected
                            ]}>
                              {item.waitingTimeType === type.kk && (
                                <View style={styles.radioInnerCircle} />
                              )}
                            </View>
                            <Text style={styles.radioText}>
                              {type.kk}
                            </Text>
                          </TouchableOpacity>
                        ))}
                      </View>
                    </View>
                    <TouchableOpacity
                      style={[styles.reportBtn, loading && styles.reportBtnDisabled]}
                      onPress={() => handleReport(idx)}
                      disabled={loading}
                    >
                      {loading ? (
                        <View style={styles.reportBtnLoading}>
                          <ActivityIndicator size="small" color="#fff" style={styles.loadingIndicator} />
                          <Text style={styles.reportBtnText}>提交中...</Text>
                        </View>
                      ) : (
                        <Text style={styles.reportBtnText}>报工</Text>
                      )}
                    </TouchableOpacity>
                  </View>
                </View>
              );
            })()}
          </ScrollView>
        )}
      </KeyboardAvoidingView>
      <Modal visible={scanVisible} animationType="slide">
        <CustomQRScanner
          onRead={onBarcodeScan}
          onClose={() => setScanVisible(false)}
        />
      </Modal>

      <Modal visible={leftScanVisible} animationType="slide">
        <CustomQRScanner
          onRead={onLeftBarcodeScan}
          onClose={() => setLeftScanVisible(false)}
        />
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#f5f5f5' },
  scrollContent: { paddingHorizontal: 10, paddingTop: 5, paddingBottom: 5 },
  title: { color: '#333', fontSize: 22, fontWeight: 'bold', alignSelf: 'center' },
  qrRow: { flexDirection: 'row', alignItems: 'center' },
  inputContainer: { flexDirection: 'row', alignItems: 'center', flex: 1 },
  qrInput: { flex: 1, borderWidth: 1, borderColor: '#ccc', borderRadius: 6, padding: 10, paddingRight: 35, backgroundColor: '#fff', height: 44 },
  clearButton: {
    position: 'absolute',
    right: 8,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    padding: 8
  },
  clearButtonText: {
    color: '#999',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    width: 20,
    height: 20,
    lineHeight: 20,
  },
  qrBtn: { marginLeft: 8 },
  qrBtn2: { marginLeft: 8, paddingHorizontal: 7, height: 44, borderWidth: 1, borderColor: '#eeee', borderRadius: 6, justifyContent: 'center', alignItems: 'center' },
  qrBtnText: { color: '#fff', fontWeight: 'bold' },
  qrBtnIcon: { width: 27, height: 27 },
  infoBox: { flexDirection: 'row', marginBottom: 20 },
  infoRow: { flexDirection: 'row', alignItems: 'center', marginBottom: 4 },
  infoLabel: { width: 80, color: '#333', fontWeight: 'bold' },
  infoValue: { flex: 1, color: '#333' },
  actionBtn: {
    paddingHorizontal: 18,
    paddingVertical: 8,
    borderRadius: 4,
    alignSelf: 'center',
    justifyContent: 'center',
    marginBottom: 16,
    marginRight: 16,
  },
  startBtn: {
    backgroundColor: '#28a745',
  },
  endBtn: {
    backgroundColor: '#dc3545',
  },
  actionText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 16,
  },
  reportBox: { marginTop: 7 },
  inputRow: { flexDirection: 'row', alignItems: 'center', marginBottom: 7 },
  inputLabel: { width: 80, color: '#333', fontWeight: 'bold' },
  input: { flex: 1, borderWidth: 1, borderColor: '#ccc', borderRadius: 6, padding: 8, backgroundColor: '#fff' },
  reportBtn: { marginTop: 7, backgroundColor: '#28a745', paddingVertical: 14, borderRadius: 6, alignItems: 'center' },
  reportBtnDisabled: { backgroundColor: '#6c757d', opacity: 0.7 },
  reportBtnLoading: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center' },
  loadingIndicator: { marginRight: 8 },
  reportBtnText: { color: '#fff', fontWeight: 'bold', fontSize: 16 },
  radioGroup: { flexDirection: 'row', flexWrap: 'wrap', flex: 1 },
  radioItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 10,
    marginBottom: 8,
    marginTop: 8,
  },
  radioCircle: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 2,
    borderColor: '#ccc',
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 8,
  },
  radioCircleSelected: {
    borderColor: '#007AFF',
  },
  radioInnerCircle: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: '#007AFF',
  },
  radioText: {
    color: '#333',
    fontSize: 14,
  },
  actionCol: {
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 16,
  },
  headerContainer: {
    backgroundColor: '#fff',
    paddingTop: getStatusBarHeight(),
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 50,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#fff',
    position: 'relative',
    zIndex: 10,
  },
  searchContainer: {
    backgroundColor: '#f5f5f5',
    paddingHorizontal: 10,
    paddingVertical: 10,
    zIndex: 9,
  },
  headerBackBtn: {
    position: 'absolute',
    left: 0,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    padding: 8,
  },
  headerLeftBtn: {
    position: 'absolute',
    left: 16,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 8,
  },
  headerRightBtn: {
    position: 'absolute',
    right: 16,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 8,
  },
  scanResultDisplay: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f0f8ff',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#007AFF',
    maxWidth: 100, // 减小整体最大宽度
  },
  scanResultText: {
    fontSize: 12, // 减小字体大小
    color: '#007AFF',
    fontWeight: 'bold',
    marginRight: 4,
    maxWidth: 70, // 给图标预留空间，文字最大宽度70
    flexShrink: 1, // 允许文字收缩
  },
  scanResultIcon: {
    width: 14,
    height: 14,
    tintColor: '#007AFF',
    flexShrink: 0, // 图标不收缩，保持固定大小
  },
  scanResultDisplayText: {
    fontSize: 14,
    color: '#333',
    flex: 1,
    paddingVertical: 8,
    paddingHorizontal: 12,
    backgroundColor: '#f5f5f5',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  emptyContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    // paddingVertical: 40,
    flex: 1,
  },
  emptyImage: {
    width: 160,
    height: 160,
    marginBottom: 16,
  },
  emptyText: {
    fontSize: 16,
    color: '#888',
    textAlign: 'center',
  },
  // 工序导航样式
  processSection: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
    elevation: 2,
    marginHorizontal: 10, // 与整体内容保持一致的左右间距
    overflow: 'visible',
    height: 90, // 增加高度以容纳对勾图标
  },
  processScrollView: {
    overflow: 'hidden',
    flex: 1,
  },
  processContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'nowrap',
    paddingRight: 2,
  },
  processItemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  processItem: {
    minWidth: 60,
    maxWidth: 120,
    height: 60,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
    marginHorizontal: 2,
    paddingHorizontal: 7,
  },
  processTextContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
  },
  processNum: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 2,
  },
  processName: {
    fontSize: 10,
    color: '#fff',
    textAlign: 'center',
    lineHeight: 12,
    flexShrink: 1,
  },
  completedIcon: {
    position: 'absolute',
    top: -7,
    right: -7,
    backgroundColor: '#007AFF',
    borderRadius: 8,
    width: 16,
    height: 16,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 10, // 确保对勾图标在最上层，不被遮挡
  },
  checkmark: {
    fontSize: 10,
    color: '#fff',
    fontWeight: 'bold',
  },
  processArrow: {
    marginHorizontal: 7,
  },
  arrowText: {
    fontSize: 16,
    color: '#007AFF',
    fontWeight: 'bold',
  },
  selectedProcessItem: {
    borderWidth: 3,
    borderColor: '#007AFF',
    elevation: 3,
    shadowColor: '#007AFF',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
  },
  // 设备选择相关样式
  deviceSelectorContainer: {
    position: 'relative',
    flex: 1,
  },
  deviceSelector: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
    borderRadius: 8,
    paddingVertical: 12,
    paddingHorizontal: 15,
    borderWidth: 1,
    borderColor: '#ddd',
    minHeight: 40,
  },
  deviceSelectorText: {
    fontSize: 16,
    color: '#333',
    flex: 1,
  },
  deviceArrow: {
    width: 16,
    height: 16,
    marginLeft: 8,
  },
  deviceDropdown: {
    position: 'absolute',
    top: 45,
    left: 0,
    right: 0,
    backgroundColor: '#fff',
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ddd',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 6,
    elevation: 4,
    zIndex: 1000,
    maxHeight: 200,
  },
  deviceScrollView: {
    maxHeight: 200,
  },
  deviceOption: {
    paddingVertical: 12,
    paddingHorizontal: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  deviceOptionText: {
    fontSize: 16,
    color: '#333',
  },
});

export default WorkReportScreen; 
